package cn.com.miao.lynx.plugin.mail;

import cn.com.miao.lynx.plugin.mail.properties.MailProperties;
import cn.com.miao.lynx.plugin.mail.service.MailService;
import cn.com.miao.lynx.plugin.mail.service.impl.AliYunMailService;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.profile.DefaultProfile;
import com.aliyuncs.profile.IClientProfile;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import static cn.com.miao.lynx.plugin.mail.properties.MailProperties.MAIL_PREFIX;

/**
 * MailAutoConfig
 *
 * @title: MailAutoConfig
 * @description:
 * @author: dengmiao
 * @create: 2020-01-10 11:49
 **/
@Slf4j
@AllArgsConstructor
@Configuration
@ConditionalOnClass(AliYunMailService.class)
@ConditionalOnProperty(prefix = MAIL_PREFIX, name = {"access-key", "access-secret", "account-name", "region"})
@EnableConfigurationProperties(MailProperties.class)
public class MailAutoConfig {

    private final MailProperties mailProperties;

    @Bean
    @ConditionalOnMissingBean
    public IAcsClient acsClient() {
        IClientProfile profile = DefaultProfile.getProfile(mailProperties.getRegion().getValue(), mailProperties.getAccessKey(), mailProperties.getAccessSecret());
        return new DefaultAcsClient(profile);
    }

    @Bean
    @ConditionalOnMissingBean
    public MailService mailService(IAcsClient acsClient) {
        return AliYunMailService.builder()
                .client(acsClient)
                .accountName(mailProperties.getAccountName())
                .replyToAddress(mailProperties.isReplyToAddress())
                .addressType(mailProperties.getAddressType())
                .defaultFromAlias(mailProperties.getFromAlias())
                .defaultTagName(mailProperties.getTagName())
                .build();
    }
}
